package com.ruyuan.user.server.controller.converter;

import com.ruyuan.gateway.sdk.facade.RuyuanGatewayFacade;
import com.ruyuan.user.api.model.enums.OrgTypeEnum;
import com.ruyuan.user.server.controller.request.SaveOrganizationRequest;
import com.ruyuan.user.server.controller.response.OrganizationTreeVO;
import com.ruyuan.user.server.domain.model.Organization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xx
 */
@Component
public class WebOrganizationConverter {

    @Autowired
    private RuyuanGatewayFacade ruyuanGatewayFacade;

    public Organization convertRequestToOrganization(SaveOrganizationRequest request) {
        Organization organization = new Organization();
        organization.setId(request.getOrgId());
        organization.setName(request.getName());
        organization.setDescription(request.getDesc());
        organization.setOrgType(OrgTypeEnum.getByCode(request.getOrgType()));
        organization.setParentId(request.getParentId());
        organization.setPriority(Optional.ofNullable(request.getPriority()).orElse(Integer.MAX_VALUE));
        Long operator = ruyuanGatewayFacade.getCurrentUser().getUserId();
        organization.setModifier(String.valueOf(operator));
        return organization;
    }

    public List<OrganizationTreeVO> convertModelToTreeVOList(List<Organization> organizations) {
        Map<Long, List<Organization>> parentIdMap = new HashMap<>();
        //构造一个map key是组织id value是该组织id的所有子节点
        organizations.forEach(it -> {
            List<Organization> organizationSameParent = parentIdMap.computeIfAbsent(it.getParentId(), parentId -> new ArrayList<>());
            organizationSameParent.add(it);
        });
        List<Organization> rootOrg = parentIdMap.get(0L);
        //多棵组织树的情况
        return rootOrg.stream().sorted(Comparator.comparingInt(Organization::getPriority))
                .map(it -> convertModelToTreeVO(it, parentIdMap)).collect(Collectors.toList());
    }

    private OrganizationTreeVO convertModelToTreeVO(Organization curOrg, Map<Long, List<Organization>> parentIdMap) {
        OrganizationTreeVO vo = new OrganizationTreeVO();
        vo.setOrgId(curOrg.getId());
        vo.setParentId(curOrg.getParentId());
        vo.setName(curOrg.getName());
        vo.setPriority(curOrg.getPriority());
        vo.setDesc(curOrg.getDescription());
        vo.setOrgType(curOrg.getOrgType().getCode());
        //有子节点不能删除
        vo.setCanDelete(!parentIdMap.containsKey(curOrg.getId()));
        //递归构造子树
        if (parentIdMap.containsKey(curOrg.getId())) {
            vo.setChildren(parentIdMap.get(curOrg.getId()).stream().sorted(Comparator.comparingInt(Organization::getPriority))
                    .map(child -> convertModelToTreeVO(child, parentIdMap)).collect(Collectors.toList()));
        }
        return vo;
    }

}
